import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import 'record_data_manager.dart';

/// 录像数据组件
/// 完全组件化的录像数据管理，不依赖特定的Controller
class RecordDataWidget extends StatefulWidget {
  final String deviceId;
  final String channelId;
  final DateTime selectedDate;
  final String sourceType; // 'cloud' 或 'local'
  final Function(List<RecordSegment>)? onDataLoaded;
  final Function(String)? onError;

  const RecordDataWidget({
    super.key,
    required this.deviceId,
    required this.channelId,
    required this.selectedDate,
    required this.sourceType,
    this.onDataLoaded,
    this.onError,
  });

  @override
  State<RecordDataWidget> createState() => _RecordDataWidgetState();
}

class _RecordDataWidgetState extends State<RecordDataWidget> {
  final RecordDataManager _recordDataManager = RecordDataManager();
  final RxBool _isLoading = false.obs;
  final RxList<RecordSegment> _recordSegments = <RecordSegment>[].obs;

  @override
  void initState() {
    super.initState();
    _loadRecordData();
  }

  @override
  void didUpdateWidget(RecordDataWidget oldWidget) {
    super.didUpdateWidget(oldWidget);

    // 当关键参数变化时重新加载数据
    if (oldWidget.deviceId != widget.deviceId ||
        oldWidget.channelId != widget.channelId ||
        oldWidget.selectedDate != widget.selectedDate ||
        oldWidget.sourceType != widget.sourceType) {
      _loadRecordData();
    }
  }

  /// 加载录像数据
  Future<void> _loadRecordData() async {
    if (widget.deviceId.isEmpty) {
      widget.onError?.call('设备ID不能为空');
      return;
    }

    _isLoading.value = true;
    _recordSegments.clear();

    try {
      final segments = await _recordDataManager.loadRecordData(
        deviceId: widget.deviceId,
        channelId: widget.channelId,
        date: widget.selectedDate,
        sourceType: widget.sourceType,
      );

      _recordSegments.addAll(segments);
      widget.onDataLoaded?.call(segments);

      print('✅ 录像数据组件加载完成，共 ${segments.length} 条记录');
    } catch (e) {
      print('❌ 录像数据组件加载失败: $e');
      widget.onError?.call('加载录像数据失败: $e');
    } finally {
      _isLoading.value = false;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      if (_isLoading.value) {
        return _buildLoadingWidget();
      }

      if (_recordSegments.isEmpty) {
        return _buildEmptyWidget();
      }

      return _buildRecordList();
    });
  }

  /// 构建加载中组件
  Widget _buildLoadingWidget() {
    return Container(
      height: 200.h,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(color: Color(0xFF047FF7)),
            SizedBox(height: 20.h),
            Text(
              '正在加载录像数据...',
              style: TextStyle(fontSize: 28.sp, color: Color(0xFF999999)),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建空数据组件
  Widget _buildEmptyWidget() {
    return Container(
      height: 200.h,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.videocam_off, size: 60.w, color: Color(0xFFCCCCCC)),
            SizedBox(height: 16.h),
            Text(
              '暂无录像数据',
              style: TextStyle(fontSize: 28.sp, color: Color(0xFF999999)),
            ),
            SizedBox(height: 8.h),
            Text(
              '${widget.sourceType == 'cloud' ? '云端' : '本地'}录像 - ${_formatDateForDisplay(widget.selectedDate)}',
              style: TextStyle(fontSize: 24.sp, color: Color(0xFFCCCCCC)),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建录像列表
  Widget _buildRecordList() {
    return ListView.builder(
      padding: EdgeInsets.symmetric(horizontal: 32.w),
      itemCount: _recordSegments.length,
      itemBuilder: (context, index) {
        final segment = _recordSegments[index];
        return _buildRecordItem(segment);
      },
    );
  }

  /// 构建录像项
  Widget _buildRecordItem(RecordSegment segment) {
    return Container(
      margin: EdgeInsets.only(bottom: 16.h),
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.05),
            offset: Offset(0, 2),
            blurRadius: 8,
          ),
        ],
      ),
      child: Row(
        children: [
          // 录像类型图标
          Container(
            width: 40.w,
            height: 40.w,
            decoration: BoxDecoration(
              color: _getTypeColor(segment.type),
              borderRadius: BorderRadius.circular(8.r),
            ),
            child: Icon(
              _getTypeIcon(segment.type),
              color: Colors.white,
              size: 20.w,
            ),
          ),
          SizedBox(width: 16.w),

          // 录像信息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '${segment.time} - ${_formatTimeRange(segment.startTime, segment.endTime)}',
                  style: TextStyle(
                    fontSize: 28.sp,
                    fontWeight: FontWeight.w500,
                    color: Color(0xFF333333),
                  ),
                ),
                SizedBox(height: 8.h),
                Row(
                  children: [
                    Text(
                      '时长: ${segment.duration}',
                      style: TextStyle(
                        fontSize: 24.sp,
                        color: Color(0xFF666666),
                      ),
                    ),
                    SizedBox(width: 16.w),
                    Container(
                      padding: EdgeInsets.symmetric(
                        horizontal: 8.w,
                        vertical: 4.h,
                      ),
                      decoration: BoxDecoration(
                        color:
                            segment.source == 'cloud'
                                ? Color(0xFFE3F2FD)
                                : Color(0xFFF3E5F5),
                        borderRadius: BorderRadius.circular(4.r),
                      ),
                      child: Text(
                        segment.source == 'cloud' ? '云端' : '本地',
                        style: TextStyle(
                          fontSize: 20.sp,
                          color:
                              segment.source == 'cloud'
                                  ? Color(0xFF1976D2)
                                  : Color(0xFF7B1FA2),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),

          // 操作按钮
          IconButton(
            onPressed: () {
              // 这里可以添加播放录像的逻辑
              print('播放录像: ${segment.id}');
            },
            icon: Icon(
              Icons.play_circle_outline,
              color: Color(0xFF047FF7),
              size: 32.w,
            ),
          ),
        ],
      ),
    );
  }

  /// 获取录像类型颜色
  Color _getTypeColor(String type) {
    switch (type) {
      case 'time':
        return Color(0xFF4CAF50);
      case 'alarm':
        return Color(0xFFFF5722);
      case 'manual':
        return Color(0xFF2196F3);
      default:
        return Color(0xFF9E9E9E);
    }
  }

  /// 获取录像类型图标
  IconData _getTypeIcon(String type) {
    switch (type) {
      case 'time':
        return Icons.schedule;
      case 'alarm':
        return Icons.warning;
      case 'manual':
        return Icons.touch_app;
      default:
        return Icons.videocam;
    }
  }

  /// 格式化时间范围
  String _formatTimeRange(DateTime start, DateTime end) {
    return '${end.hour.toString().padLeft(2, '0')}:${end.minute.toString().padLeft(2, '0')}';
  }

  /// 格式化日期显示
  String _formatDateForDisplay(DateTime date) {
    return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
  }
}
